from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from django.db.models import Q
from .models import Interface, Case
from .serializers import InterfaceSerializer, CaseSerializer
import os
import sys
from django.conf import settings

# 导入PyAllure API
sys.path.append(os.path.join(settings.BASE_DIR, 'PyAllure'))
from PyAllure.api import PyAllureAPI


class CasePagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'size'
    max_page_size = 100
    
    def get_paginated_response(self, data):
        return Response({
            'status': 200,
            'data': {
                'results': data,
                'count': self.page.paginator.count,
                'next': self.get_next_link(),
                'previous': self.get_previous_link()
            }
        })


class InterfaceViewSet(viewsets.ModelViewSet):
    queryset = Interface.objects.all()
    serializer_class = InterfaceSerializer
    
    def get_queryset(self):
        """可以按项目ID过滤接口"""
        queryset = Interface.objects.all()
        project_id = self.request.query_params.get('project_id')
        if project_id:
            queryset = queryset.filter(project_id=project_id)
        return queryset


class CaseViewSet(viewsets.ModelViewSet):
    queryset = Case.objects.all()
    serializer_class = CaseSerializer
    pagination_class = CasePagination
    
    def get_queryset(self):
        """可以按项目ID或接口ID过滤用例，支持搜索"""
        queryset = Case.objects.all()
        
        # 按项目ID过滤
        project_id = self.request.query_params.get('project_id')
        if project_id:
            queryset = queryset.filter(project_id=project_id)
        
        # 按接口ID过滤
        interface_id = self.request.query_params.get('interface_id')
        if interface_id:
            queryset = queryset.filter(interface_id=interface_id)
        
        # 按标题搜索
        title = self.request.query_params.get('title')
        if title:
            queryset = queryset.filter(title__icontains=title)
        
        # 按请求方法过滤
        method = self.request.query_params.get('method')
        if method:
            queryset = queryset.filter(method=method)
        
        # 按优先级过滤
        priority = self.request.query_params.get('priority')
        if priority:
            queryset = queryset.filter(priority=priority)
            
        return queryset.order_by('-created_time')
    
    def list(self, request, *args, **kwargs):
        """获取用例列表"""
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'status': 200,
            'data': {
                'results': serializer.data,
                'count': len(serializer.data)
            }
        })
    
    def create(self, request, *args, **kwargs):
        """创建用例"""
        data = request.data.copy()
        
        # 如果没有提供interface，创建一个默认的interface
        if 'interface' not in data or not data['interface']:
            from .models import Interface
            interface = Interface.objects.create(
                name=data.get('title', 'API'),
                project_id=data['project'],
                method=data.get('method', 'GET'),
                url=data.get('url', '/')
            )
            data['interface'] = interface.id
        
        # 设置name字段（如果没有提供）
        if not data.get('name'):
            data['name'] = data.get('title', 'Test Case')
            
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        
        return Response({
            'status': 201,
            'data': serializer.data,
            'msg': '用例创建成功'
        }, status=status.HTTP_201_CREATED)
    
    def update(self, request, *args, **kwargs):
        """更新用例"""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        data = request.data.copy()
        
        # 设置name字段（如果没有提供）
        if not data.get('name'):
            data['name'] = data.get('title', instance.name)
            
        serializer = self.get_serializer(instance, data=data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        
        return Response({
            'status': 200,
            'data': serializer.data,
            'msg': '用例更新成功'
        })
    
    def destroy(self, request, *args, **kwargs):
        """删除用例"""
        instance = self.get_object()
        case_title = instance.title
        self.perform_destroy(instance)
        
        return Response({
            'status': 200,
            'msg': f'用例"{case_title}"删除成功'
        }, status=status.HTTP_200_OK)
    
    @action(detail=True, methods=['post'])
    def generate_yaml(self, request, pk=None):
        """生成YAML文件"""
        case = self.get_object()
        yaml_content = case.to_yaml()
        
        return Response({
            'yaml_content': yaml_content
        })
        
    @action(detail=True, methods=['post'])
    def execute(self, request, pk=None):
        """执行测试用例并记录执行状态和结果"""
        from .models import CaseExecutionRecord
        case_id = pk or request.data.get('case_id')
        if not case_id:
            return Response({"error": "必须提供case_id"}, status=status.HTTP_400_BAD_REQUEST)
        try:
            case = Case.objects.get(id=case_id)
        except Case.DoesNotExist:
            return Response({"error": "测试用例不存在"}, status=status.HTTP_404_NOT_FOUND)
        # 创建执行记录，初始为running
        record = CaseExecutionRecord.objects.create(case=case, status='running')
        try:
            from PyAllure.api import PyAllureAPI
            PyAllureAPI.clean_testcases_dir()
            case_data = PyAllureAPI.convert_django_case(case)
            file_name = f"test_{case.id}_{case.name}.yaml"
            PyAllureAPI.create_test_yaml(case_data, file_name)
            result = PyAllureAPI.run_tests()
            success = (result == 0)
            record.status = 'success' if success else 'failed'
            record.result = '测试执行成功' if success else '测试执行失败'
            record.report_url = '/reports/index.html'
            record.save()
            return Response({
                'success': success,
                'message': record.result,
                'report_url': record.report_url,
                'execution': {
                    'status': record.status,
                    'result': record.result,
                    'report_url': record.report_url,
                    'created_at': record.created_at,
                }
            })
        except Exception as e:
            import traceback
            record.status = 'failed'
            record.result = str(e)
            record.save()
            print(traceback.format_exc())
            return Response({
                'success': False,
                'message': '测试执行出错',
                'error': str(e),
                'execution': {
                    'status': record.status,
                    'result': record.result,
                    'created_at': record.created_at,
                }
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
